package com.promise.jokerdream.task

import com.promise.jokerdream.task.base.NetworkStep
import com.promise.jokerdream.task.base.SerialTask
import com.promise.jokerdream.task.base.TaskType
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit

/**
 * 定时执行的任务
 */
class ScheduledTask(
    name: String,
    private val scheduledTime: LocalDateTime,
    repeatCount: Int = 1,
    private val networkAction: suspend () -> Unit
) : SerialTask(name, TaskType.SCHEDULED, repeatCount) {
    
    /**
     * 是否已到执行时间
     */
    val isTimeToExecute: Boolean
        get() = LocalDateTime.now().isAfter(scheduledTime) || LocalDateTime.now().isEqual(scheduledTime)
    
    /**
     * 距离执行时间还有多少毫秒
     */
    val delayMillis: Long
        get() {
            val now = LocalDateTime.now()
            return if (now.isBefore(scheduledTime)) {
                ChronoUnit.MILLIS.between(now, scheduledTime)
            } else {
                0L
            }
        }
    
    /**
     * 获取调度时间
     */
    fun getScheduledTime(): LocalDateTime = scheduledTime
    
    override fun getSteps(): List<NetworkStep> {
        return listOf(SimpleNetworkStep("scheduled_action", networkAction))
    }
    
    override fun getRepeatInterval(): Long = TaskConfig.REPEAT_INTERVAL
    
    companion object {
        /**
         * 创建定时任务
         */
        fun create(
            name: String,
            scheduledTime: LocalDateTime,
            repeatCount: Int = 1,
            networkAction: suspend () -> Unit
        ): ScheduledTask {
            return ScheduledTask(name, scheduledTime, repeatCount, networkAction)
        }
    }
}

